<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\common\service\qrcode;

/**
 * 礼品核销二维码
 * Class Extract
 * @package app\common\service\qrcode
 */
class Coupon extends BaseQRcode {
	// 当前客户端 (默认H5)
	private $channel;

	// 当前用户信息
	private $user;

	// 订单ID
	private $CouponId;

	/**
	 * 构造方法
	 * Extract constructor.
	 * @param string $channel 二维码渠道(小程序码、h5码)
	 * @param $user
	 * @param $CouponId
	 */
	public function __construct($user, $CouponId) {
		parent::__construct();
		$this->user = $user;
		$this->CouponId = $CouponId;
		$this->channel = 'MP-WEIXIN';
	}

	/**
	 * 获取小程序码
	 * @return string
	 * @throws \app\common\exception\BaseException
	 * @throws \cores\exception\BaseException
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function getImage(): string {
		// 判断二维码文件存在则直接返回url
		if (file_exists($this->getPosterPath())) {
			// return $this->getPosterUrl();
		}
		// 下载二维码
		$scene = "oid:{$this->CouponId}";
		//$qrcode = $this->getQrcode($this->storeId, $scene, 'pages/my-coupon/check', $this->channel);
		$qrcode = $this->getQrcode($this->storeId, $scene, 'pages/my-coupon/index', $this->channel);
		return $this->savePoster($qrcode);
	}

	/**
	 * 保存并获取图片
	 * @param $qrcode
	 * @return string
	 */
	private function savePoster($qrcode): string {
		copy($qrcode, $this->getPosterPath());
		return $this->getPosterUrl();
	}

	/**
	 * 二维码文件路径
	 * @return string
	 */
	private function getPosterPath(): string {
		// 保存路径
		$tempPath = web_path() . "temp/{$this->storeId}/";
		!is_dir($tempPath) && mkdir($tempPath, 0755, true);
		return $tempPath . $this->getPosterName();
	}

	/**
	 * 二维码文件名称
	 * @return string
	 */
	private function getPosterName(): string {
		return 'coupon_' . md5("{$this->CouponId}_{$this->user['user_id']}_{$this->channel}") . '.png';
	}

	/**
	 * 二维码url
	 * @return string
	 */
	private function getPosterUrl(): string {
		return base_url() . 'temp/' . $this->storeId . '/' . $this->getPosterName() . '?t=' . time();
	}
}
